<template>
  <div class="app-container" ref="appContainer">
    <commonTable
      :loading="loading"
      @selection-change="selectionChange"
      :columns="column"
      :data="list"
      @reset="reset"
      @onSubmit="onSubmit"
    >
      <template v-slot:btn>
        <div style="display: flex; justify-content: flex-end">
          <el-button type="primary" @click="add"
            ><el-icon><plus /></el-icon> 添加</el-button
          >
          <el-button type="danger" @click="batchDelete"
            ><el-icon><delete /></el-icon>删除</el-button
          >
        </div>
      </template>
      <template v-slot:state="scope">{{ scope.row.state ? '审核通过' : '审核不通过' }}</template>
      <template v-slot:operation="scope">
        <el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
          编辑
        </el-button>
        <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
          删除
        </el-button>
      </template>
    </commonTable>

    <el-dialog v-model="dialogVisible" :title="title" width="50%">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="活动名称" prop="cusName">
          <el-input v-model="ruleForm.cusName" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="ruleForm.state">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="0">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="价格" prop="applyUser">
          <el-input v-model="ruleForm.applyUser" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, reactive, onMounted, nextTick } from 'vue'
  // import * as dayjs from 'dayjs'
  import dayjs from 'dayjs'
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
  const loading = ref(true)
  const appContainer = ref(null)
  import commonTable from '@/components/commonTable/index.vue'
  import { tableMock } from '@/api'
  // 自定义接口入参，待联调
  const cusId = 88888888
  const list = ref([])
  // 请求表格数据
  tableMock({ cusId })
    .then((res) => {
      console.log('tableData', res)
      list.value.push(...res.data)
    })
    .catch((err) => {
      console.log(err)
    })
  const column = [
    { type: 'selection', width: 60, fixed: 'left' },
    { name: 'operation', slot: true, fixed: 'right', width: 200, label: '操作' },
    { name: 'cusName', label: '客户名', inSearch: true, valueType: 'input', width: 80 },
    {
      name: 'organize',
      label: '所属机构',
      inSearch: true,
      valueType: 'input',
      align: 'center',
      width: 100,
    },
    { name: 'applyUser', label: '申请用户', valueType: 'input', width: 100 },
    {
      name: 'date',
      label: '申请时间',
      sorter: true,
      inSearch: true,
      valueType: 'input',
      width: 180,
    },
    {
      name: 'state',
      label: '状态',
      slot: true,
      inSearch: true,
      options: [
        {
          value: 1,
          label: '审核通过',
        },
        {
          value: 0,
          label: '审核不通过',
        },
      ],
      valueType: 'select',
      width: 100,
    },
    {
      name: 'realState',
      label: '实人认证状态',
      inSearch: true,
      options: [
        {
          value: 0,
          label: '认证成功',
        },
        {
          value: 1,
          label: '认证失败',
        },
        {
          value: 2,
          label: '未认证',
        },
      ],
      valueType: 'select',
      width: 180,
    },
    {
      name: 'sucessCount',
      label: '实人认证成功次数',
      valueType: 'input',
      width: 180,
    },
    { name: 'failCount', label: '实人认证失败次数', width: 180 },
    { name: 'riskResult', label: '风控结果', width: 100 },
    { name: 'reason', label: '原因' },
    {
      name: 'type',
      label: '入网类型',
      inSearch: true,
      options: [
        {
          value: 0,
          label: '线上入网',
        },
        {
          value: 1,
          label: '线下入网',
        },
      ],
      valueType: 'select',
      width: 100,
    },
    {
      name: 'riskRank',
      label: '风险等级',
      inSearch: true,
      valueType: 'select',
      options: [
        {
          value: 0,
          label: '低级',
        },
        {
          value: 1,
          label: '中级',
        },
        {
          value: 2,
          label: '高级',
        },
      ],
      width: 100,
    },
    { name: 'channel', label: '伞形账户渠道', width: 150 },
    { name: 'currency', label: '伞形账户币种', width: 150 },
  ]

  const formSize = ref('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive({
    cusName: '',
    state: null,
    applyUser: null,
  })

  const rules = reactive({
    cusName: [
      { required: true, message: '请输入活动名称活动区域', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
    ],
    applyUser: [{ required: true, message: '请输入用户', trigger: 'blur' }],
    state: [
      {
        required: true,
        message: '请选择状态',
        trigger: 'change',
      },
    ],
  })

  const dialogVisible = ref(false)
  const title = ref('新增')
  const rowObj = ref({})
  const selectObj = ref([])

  const handleClose = async (done: () => void) => {
    await ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        let obj = {
          id: Date.now(),
          ...ruleForm,
          organize: 0,
          riskResult: '添加风险结果',
          sucessCount: '添加成功次数',
          reason: '添加原因',
          failCount: '添加失败次数',
          realState: '添加实人状态',
          date: '添加' + dayjs().format('YYYY-MM-DD'),
        }
        if (title.value === '新增') {
          list.value = [obj, ...list.value]
          ElMessage.success('添加成功')
        } else {
          list.value.forEach((item) => {
            if (item?.id === rowObj.value.id) {
              item.cusName = obj.cusName
              item.state = obj.state
              item.applyUser = obj.applyUser
            }
          })
        }
        dialogVisible.value = false
        console.log('submit!', obj)
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const add = () => {
    title.value = '新增'
    dialogVisible.value = true
  }

  const batchDelete = () => {
    if (!selectObj.value.length) {
      return ElMessage.error('未选中任何行')
    }
    ElMessageBox.confirm('你确定要删除选中项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(() => {
        ElMessage.success('模拟删除成功')
        list.value = list.value.concat([])
      })
      .catch(() => {})
  }
  const selectionChange = (val) => {
    selectObj.value = val
  }

  const edit = (row) => {
    title.value = '编辑'
    rowObj.value = row
    dialogVisible.value = true
    ruleForm.cusName = row.cusName
    ruleForm.state = row.state
    ruleForm.applyUser = row.applyUser
  }

  const del = (row) => {
    console.log('row==', row)
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(() => {
        list.value = list.value.filter((item) => item.id !== row.id)
        ElMessage.success('删除成功')
        loading.value = true
        setTimeout(() => {
          loading.value = false
        }, 500)
      })
      .catch(() => {})
  }

  const reset = () => {
    loading.value = true
    setTimeout(() => {
      loading.value = false
    }, 500)
    ElMessage.success('触发重置方法')
  }

  const onSubmit = (val) => {
    console.log('val===', val)
    ElMessage.success('触发查询方法')
    loading.value = true
    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  const getHeight = () => {}

  onMounted(() => {
    nextTick(() => {
      // let data = appContainer.value.
    })
    setTimeout(() => {
      loading.value = false
    }, 500)
  })
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
